package com.example.threadmodel.model;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 如：threadName:ACTION_THREAD--p-2-t-5，则表示是第2个线程中第5个线程
 */
public class NamedPoolThreadFactory implements ThreadFactory {
    // 池子序号自增(第几个线程池)
    private static final AtomicInteger poolNum = new AtomicInteger(1);

    // 生成的线程序号自增(这个线程中第几个线程)
    private final AtomicInteger threadNum = new AtomicInteger(1);

    private final ThreadGroup group;
    private final String namePre;
    private final boolean isDaemon;

    public NamedPoolThreadFactory(String prefix) {
        this(prefix, true);
    }

    public NamedPoolThreadFactory(String prefix, boolean daemon) {
        SecurityManager manager = System.getSecurityManager();

        if (manager != null) {
            group = manager.getThreadGroup();
        } else {
            group = Thread.currentThread().getThreadGroup();
        }

        isDaemon = daemon;
        namePre = prefix + "-p" + poolNum.getAndIncrement() + "-t";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePre + threadNum.getAndIncrement(), 0);

        t.setContextClassLoader(NamedPoolThreadFactory.class.getClassLoader());
        t.setPriority(Thread.NORM_PRIORITY);
        t.setDaemon(isDaemon);
        return t;
    }
}